package main

import (
	"database/sql"
	"io"
	"log"

	"github.com/gin-gonic/gin"

	_ "github.com/go-sql-driver/mysql"
)

// 预处理
func initializeDatabase() (*sql.DB, error) {
	dsn := "root:123456@tcp(localhost:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := sql.Open("mysql", dsn)

	if err != nil {
		return nil, err
	}
	// 建立连接
	if err = db.Ping(); err != nil {
		log.Println("connect 2 database fail...")
		return nil, io.EOF
	}
	return db, nil
}

type users struct {
	Id   uint64 `json:"id"`
	Name string `json:"name"`
	Age  uint32 `json:"age"`
}

// 查询单条数据
func querySingleRow(db *sql.DB, id string) users {
	sqlStr := "select  * from users where id = ?"

	prepare, err := db.Prepare(sqlStr)
	var u users
	if err != nil {
		log.Printf("prepare faild err：%v\n", err)
		return u
	}
	defer prepare.Close()
	query, err := prepare.Query(id)
	if err != nil {
		log.Printf("query faild err：%v\n", err)
		return u
	}
	defer query.Close()

	for query.Next() {
		err := query.Scan(&u.Id, &u.Name, &u.Age)
		if err != nil {
			log.Printf("result faild err：%v\n", err)
			return u
		}

	}

	log.Printf("查询结果：%v,%v,%v", u.Id, u.Name, u.Age)
	return u
}

func deleteRow(db *sql.DB) {
	sqlStr := "delete from users where id= ?"
	res, err := db.Exec(sqlStr, 1)
	if err != nil {
		log.Printf("deleteRow faild err：%v\n", err)
		panic(err)

	}
	n, err := res.RowsAffected()
	if err != nil {
		log.Printf("get RowsAffected faild err：%v\n", err)
		panic(err)

	}
	log.Printf("deleteRow 受影响的行数：%v\n", n)
	log.Println("deleteRow success")

}

func insertRow(db *sql.DB) {
	sqlStr := "insert into users (id,name,age) values (?,?,?)"
	prepare, err := db.Prepare(sqlStr)
	if err != nil {
		log.Printf("insertRow prepare faild err：%v\n", err)
	}
	defer prepare.Close()
	exec, err := prepare.Exec(8, "小八", 70)
	if err != nil {
		log.Printf("insertRow exec faild err：%v\n", err)
	}
	id, err := exec.LastInsertId()
	if err != nil {
		log.Printf("insertRow LastInsertId faild err：%v\n", err)
	}
	log.Printf("insert success. id: %v\n", id)
}
func main() {
	db, err := initializeDatabase()
	if err != nil {
		panic(err)
	}
	log.Println("connect 2 database success.")
	r := gin.Default()
	// 查询单行
	r.GET("user/:id", func(c *gin.Context) {
		idP := c.Param("id")
		u := querySingleRow(db, idP)
		c.JSON(200, gin.H{
			"data": u,
		})
	})

	insertRow(db)
	r.Run()
}
